import { loadResourceDetailAPI, loadResourcePaceAPI } from "@/api/ResourceAPI";
import { cancelUploadAPI, heartBeatsAPI, initializeTheRepositoryAPI, SplicingChunksAPI, uploadChunkAPI } from "@/api/UploadAPI";
import { Doorplate, Filters, ResourceDetail, SearchCondition, UploadResourceChunk, UploadResourceInformation } from "@/model/ResourceModels";
import { Ref } from "vue";
import { toBase64 } from "./Utils";

// 加载分页数据
export const loadResourcePageToBack = async (query: string, finalFilters: Filters, pageIndex: number, isSearch: boolean) => {
    console.log(`搜索关键词:${query}, 筛选条件:${JSON.stringify(finalFilters)}, 加载第 ${pageIndex} 页的数据...`)

    //封装查询条件 
    const searchCondition: SearchCondition = {
        isSearch: isSearch,
        query: query,
        filters: finalFilters,
        pageIndex: pageIndex
    };

    const result = await loadResourcePaceAPI(searchCondition);
    if (result === null) {
        throw new Error("无法加载资源页面");
    }
    return result
}

// 获取资源详情
export const fetchResourceDetail = async (resource: Ref<ResourceDetail>) => {

    console.log('查看资源细节id:', resource.value.id)
    const result = await loadResourceDetailAPI(resource.value.id)
    if (result === null) {
        throw new Error("无法加载资源细节")
    }
    resource.value = result
}


export const uploadResourceToBack = async (
    file: File,
    form: UploadResourceInformation,
    uploading: Ref<boolean>,
    progress: Ref<number>,
    status: Ref<string>,
    modalVisible: Ref<boolean>,
    showProgress: Ref<boolean>,
    isCancelled: Ref<boolean>
): Promise<boolean> => {
    modalVisible.value = true
    uploading.value = true
    showProgress.value = true
    progress.value = 0
    status.value = '正在初始化仓库...'
    console.log("仓库初始化中...")
    const initializeResult = await initializeTheRepositoryAPI(form.userId)
    if (!initializeResult) {
        if (isCancelled.value) {
            isCancelled.value = false
            console.log("上传被取消，停止上传")
            return false
        }
        status.value = '初始化仓库失败正在重新初始化...'
        console.log("无法初始化仓库，重新初始化中...")
        const result = await initializeTheRepositoryAPI(form.userId)
        if (!result) {
            if (isCancelled.value) {
                isCancelled.value = false
                console.log("上传被取消，停止上传")
                return false
            }
            console.log("无法初始化仓库，上传失败")
            status.value = '初始化仓库失败'
            uploading.value = false
            showProgress.value = false
            return false
        } else {
            form.secondaryPath = result
        }
    } else {
        form.secondaryPath = initializeResult
    }

    const doorplate: Doorplate = {
        userId: form.userId,
        secondaryPath: form.secondaryPath
    }
    let beat = setInterval(async () => {
        console.log("开始心跳...")
        if (uploading.value === true) {
            const result = await heartBeatsAPI(doorplate)
            if (result === false) {
                console.warn(`心跳失败:${doorplate.userId}:${doorplate.secondaryPath}`)
            } else {
                console.log(`心跳一次:${doorplate.userId}:${doorplate.secondaryPath}`)
            }
        } else {
            clearInterval(beat)
        }
    }, 1000 * 60 * 10)

    console.log("开始上传块...")
    const chunkSize = 1 * 1024 * 1024 // 每块1MB
    const totalChunks = Math.ceil(file.size / chunkSize)
    let reupload = 0

    for (let currentChunkIndex = 0; currentChunkIndex < totalChunks;) {

        if (isCancelled.value) {
            cancelUploadAPI(doorplate)
            isCancelled.value = false
            clearInterval(beat)
            console.log("上传被取消，停止上传")
            return false
        }

        const start = currentChunkIndex * chunkSize;
        const end = Math.min(file.size, start + chunkSize);
        const chunk = file.slice(start, end);

        status.value = '上传分片' + (currentChunkIndex + 1) + '/' + totalChunks
        progress.value = ((currentChunkIndex + 1) / totalChunks) * 100

        // 发送时调用：
        const base64Chunk = await toBase64(chunk);


        const uploadChunk: UploadResourceChunk = {
            userId: form.userId,
            secondaryPath: form.secondaryPath,
            chunkTotalNumber: totalChunks,
            chunkIndex: currentChunkIndex,
            chunk: base64Chunk
        }

        const result = await uploadChunkAPI(uploadChunk)
        if (result === true) {
            console.log(`上传成功index:${currentChunkIndex}`)
            currentChunkIndex++
            reupload = 0
        } else {
            reupload++
            console.warn(`上传失败index:${currentChunkIndex}, 重试次数:${reupload}/3`)
        }
        if (reupload >= 3) {
            console.warn(`上传失败index:${currentChunkIndex},重试次数已达上限，停止上传`)
            status.value = '上传失败'
            uploading.value = false
            showProgress.value = false
            clearInterval(beat)
            cancelUploadAPI(doorplate)
            return false
        }
    }

    console.log("开始拼接上传的分片...")
    status.value = '开始拼接上传的分片...'
    const startSplicing = await SplicingChunksAPI(form)
    if (startSplicing === false) {
        console.warn(`拼接失败，正在重试`)
        const result = await SplicingChunksAPI(form)
        if (result === true) {
            status.value = '上传成功'
            uploading.value = false
            showProgress.value = false
            console.log("上传成功...")
        } else {
            console.warn(`拼接失败，重试次数已达上限，停止上传`)
            status.value = '上传失败，请重试'
            uploading.value = false
            showProgress.value = false
            clearInterval(beat)
            cancelUploadAPI(doorplate)
            return false
        }
    } else {
        status.value = '上传成功'
        uploading.value = false
        showProgress.value = false
        console.log("上传成功...")
    }
    clearInterval(beat)
    return true
}